'use strict';
const nodeRsa = require('node-rsa');
const Controller = require('egg').Controller;

class AppController extends Controller {
  get rules() {
    return {
      id: {
        type    : 'string', required: false, format  : /\d*/,
      },
      pageSize: {
        page: {
          type    : 'string', required: false, format  : /\d*/,
        },
        size: {
          type    : 'string', required: false, format  : /\d*/,
        },
        content: 'string?',
      },
      pageSizeToNumber(query) {
        let { page, size } = query;
        page = page ? Number(page) : undefined;
        size = size ? Number(size) : undefined;
        return {
          size,
          page,
        };
      },
      client: {
        clientId    : { type: 'string', format: /^\S{12}$/, required: false, allowEmpty: true },
        clientSecret: { type: 'string', format: /^\S{12}$/, required: false, allowEmpty: true },
        // grants      : /^authorization_code$/,
        url         : 'string',
        redirectUri : 'string',
        publicKey   : 'string?',
        privateKey  : 'string?',
        name        : 'string',
      },
      clientUpdate: {
        clientId    : /^\S{12}$/,
        clientSecret: /^\S{12}$/,
        // grants      : /^authorization_code$/,
        url         : 'string',
        redirectUri : 'string',
        publicKey   : 'string?',
        privateKey  : 'string?',
        name        : 'string',
      },
      applyClient: {
        name       : 'string',
        url        : /^http[s]?/,
        redirectUri: /^http[s]?/,
        applyReason: 'string',
        email      : 'email',
        // icon       : 'string',
      },
    };
  }
  /**
   * 申请应用数据界面
   */
  async applyHtml() {
    await this.ctx.render('applyClient');
  }

  /**
   * 申请应用数据
   */
  async applyClient() {
    const { ctx, rules } = this;
    const {
      name, url, redirectUri, applyReason, icon, email,
    } = ctx.helper.validate(rules.applyClient, ctx.request.body);
    try {
      await ctx.helper.sendMsg('申请应用数据', JSON.stringify({ name, url, redirectUri, applyReason, icon, email }));
      ctx.body = { result: 0, msg: 'ok' };
    } catch (err) {
      ctx.logger.error(`applyClient err ${err}`);
      ctx.body = { result: 1, msg: '异常' };
    }
  }
  /**
   * 分页查找应用
   */
  async index() {
    const { ctx, service, rules } = this;
    const { page = 1, size = 10, content } = ctx.helper.validate(rules.pageSize, ctx.query, rules.pageSizeToNumber);
    const { count, rows } = await service.client.getPage(page, size, content);
    ctx.body = {
      result: 0,
      msg   : 'ok',
      count,
      rows,
    };
  }

  /**
   * 创建应用
   */
  async create() {
    const { ctx, service, rules } = this;
    const {
      name, clientId, clientSecret, grants = 'authorization_code', url, redirectUri,
      publicKey, privateKey, lid, userEmail,
    } = ctx.helper.validate(rules.client, ctx.request.body);
    ctx.body = await service.client.create(name, clientId, clientSecret,
      grants, url, redirectUri, publicKey, privateKey, lid, userEmail);
  }
  /**
   * 删除应用信息
   */
  async delete() {
    const { ctx, service } = this;
    const { id } = ctx.helper.validate({
      id: /^\d*$/,
    }, ctx.params);
    ctx.body = await service.client.delete(Number(id));
  }

  /**
   * 更新应用信息
   */
  async update() {
    const { ctx, service, rules } = this;
    const {
      name, clientId, clientSecret, grants, url, redirectUri, publicKey, privateKey, lid, userEmail,
    } = ctx.helper.validate(rules.clientUpdate, ctx.request.body);
    const { id } = ctx.helper.validate({
      id: /^\d*$/,
    }, ctx.params);
    ctx.body = await service.client.update(Number(id), name, clientId, clientSecret,
      grants, url, redirectUri, publicKey, privateKey, lid, userEmail);
  }
  async test() {
    const client = await this.app.model.Client.findOne({ where: { id: 8 } });
    // console.log(client);
    let { publicKey } = client;
    publicKey = decodeURIComponent(publicKey);
    const key = new nodeRsa(publicKey);
    this.ctx.body = key.encrypt(123);
  }
}

module.exports = AppController;
